package cn.jsxz.controller;

import cn.jsxz.common.constants.Constants;
import cn.jsxz.common.utils.DateTimeUtil.DateUtil;
import cn.jsxz.common.utils.HttpRequsetUtil.HttpClient;
import cn.jsxz.common.utils.ResultUtil;
import cn.jsxz.common.utils.SendMessageUtil.SendSMS;
import cn.jsxz.common.utils.WeiXinUtil.WxPayUtil;
import cn.hutool.setting.dialect.Props;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;

/**
 * @auther: Zy
 * @method SendMessageApi
 * 功能描述: 发送短信通知
 * @date: 2019
 */
@RestController
@RequestMapping("/api/send")
public class SendMessageApi {


    /**
     * @auther: Zy
     * @method sendVerificationCode
     * 功能描述: 发送短信验证
     * @params: [request]
     * @return: * @return : com.alibaba.fastjson.JSONObject
     */
    @RequestMapping(value = "sendVerificationCode", method = RequestMethod.POST)
    public JSONObject sendVerificationCode(@RequestParam(value = "phone") String phone, HttpServletRequest request) {
        String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);// 生成短信验证码
        // 短信内容
        String msg = "【XXXXX】您正在进行账号的相关操作，您的验证码是：" + verifyCode + "，请于10分钟内正确输入，不能告诉别人哦！";
        SendSMS sendSMS = new SendSMS();
        boolean flag = sendSMS.sendShortMessage(phone, msg);
        if (flag) {
            // 短信验证实体
//            Authcode authcode = new Authcode();
//            authcode.setAuthCodePhone(phone);
//            authcode.setCode(verifyCode);
//            authcode.setAuthCodeTime(DateUtil.getNowTime());
//            Authcode athcodes = authcodeService.getOne(new QueryWrapper<Authcode>().eq("authCodePhone", phone));
//            if (athcodes != null) {
//                // 新增
//                authcodeService.save(athcodes);
//            }
            return ResultUtil.resultJSON(Constants.HTTP_STATE_CODE.SUCCESS_200, Constants.HTTP_STATE_MASSAGE.SUCCESS_200_MSG, null);
        } else {
            return ResultUtil.resultJSON(Constants.HTTP_STATE_CODE.ERROR_400, "发送失败", null);
        }
    }

    /**
     * @auther: Zy
     * @method sendMsgCode
     * 功能描述: 云通讯发送短信
     * @params: [phone]
     * @return: * @return : com.alibaba.fastjson.JSONObject
     * @date: 2019-01-21 11:51:14
     */
    @RequestMapping(value = "sendMsgCode", method = RequestMethod.POST)
    public JSONObject sendMsgCode(String phone) {
        Props props = new Props("workConfig.properties", "utf-8");
        String yunUrl = props.getStr("yun_url");//请求地址
        String yunId = props.getStr("yun_Id");//企业ID
        String yunAccount = props.getStr("yun_account");//用户帐号，由系统管理员
        String yunPassword = props.getStr("yuun_password");//用户账号对应的密码
        String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);// 生成短信验证码
        // 短信内容
        String msg = "【易盐购】本次登录的验证码为" + verifyCode;
        HashMap<String, String> map = new LinkedHashMap<>();
        map.put("action", "send");//设置为固定的:send
        map.put("userid", yunId);//企业ID
        map.put("account", yunAccount);//用户帐号，由系统管理员
        map.put("password", yunPassword);//用户账号对应的密码
        map.put("mobile", phone);//发信发送的目的号码.多个号码之间用半角逗号隔开
        map.put("content", msg);//短信的内容
        map.put("checkcontent", "0");//当设置为1时表示需要检查，默认0为不检查
        String result = HttpClient.sendData4Post(yunUrl, map);
        System.out.println(result);
        Map<String, String> resultMap = WxPayUtil.readStringXmlOut(result);
        String status = resultMap.get("returnstatus");
        if ("Success".equals(status)) {
//            Authcode authcode = new Authcode();
//            authcode.setAuthCodePhone(phone);
//            authcode.setCode(verifyCode);
//            authcode.setAuthCodeTime(DateUtil.getNowTime());
//            Authcode authCodePhone = authcodeService.getOne(new QueryWrapper<Authcode>().eq("authCodePhone", phone));
            boolean b = false;
//            if (authCodePhone == null) {
//                b = authcodeService.save(authcode);
//            } else {
//                authCodePhone.setAuthCodePhone(phone);
//                authCodePhone.setCode(verifyCode);
//                authCodePhone.setAuthCodeTime(DateUtil.getNowTime());
//                b = authcodeService.updateById(authCodePhone);
//            }
            if (b) {
                return ResultUtil.resultJSON(Constants.HTTP_STATE_CODE.SUCCESS_200, Constants.HTTP_STATE_MASSAGE.SUCCESS_200_MSG, null);
            }
        }
        return ResultUtil.resultJSON(Constants.HTTP_STATE_CODE.ERROR_400, "发送失败", null);
    }

    //hppt post请求试例
    @RequestMapping(value = "test")
    public void test() {
        String yunUrl = "http://www.lcdxw.com/sms.aspx";//请求地址
        String yunId = "4360";//企业ID
        String yunAccount = "a13952200096";//用户帐号，由系统管理员
        String yuunPassword = "a13952200096";//用户账号对应的密码
        String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);// 生成短信验证码
        // 短信内容
//        String msg = "【盐易购】您正在进行账号的相关操作，您的验证码是：" + verifyCode + "，请于10分钟内正确输入，不能告诉别人哦！";
        String msg = "【易盐购】本次登录的验证码为" + verifyCode;
        HashMap<String, String> map = new LinkedHashMap<>();
        map.put("action", "send");//设置为固定的:send
        map.put("userid", yunId);//企业ID
        map.put("account", yunAccount);//用户帐号，由系统管理员
        map.put("password", yuunPassword);//用户账号对应的密码
        map.put("mobile", "13101829291");//发信发送的目的号码.多个号码之间用半角逗号隔开
        map.put("content", msg);//短信的内容
        map.put("checkcontent", "0");//当设置为1时表示需要检查，默认0为不检查
        System.out.println(map);
        org.apache.http.client.HttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(yunUrl);
        String result = "";
        cn.hutool.json.JSONObject obj = null;
        ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            param.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        try {
            post.setEntity(new UrlEncodedFormEntity(param, "UTF-8"));
            HttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, "UTF-8");
            System.out.println(result);
            obj = new cn.hutool.json.JSONObject(JSON.parse(result));
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        }
    }
}
